﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Drawing;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.ServiceModel;
using System.Net;
//using global::StuCat.ServiceRef;
using StudioLib;
namespace StuCat
{
    public partial class MainWindow : Form
    {
        private List<Studio> Catalog = new List<Studio>();
        
        private Studio viewedStudio { get { return Catalog[listStudio.SelectedIndex]; } }

        private void SaveList()
        {
            Log.LogInfo("Saving Studios.stc");
            
            using (FileStream listFile = File.Create("Studios.stc"))
            {
                new BinaryFormatter().Serialize(listFile, Catalog);    
            }                        
        }

        private int LoadList()
        {
            Log.LogInfo("Loading Studios.stc ...");

            BinaryFormatter BF = new BinaryFormatter();
            
            try
            {
                using(FileStream file = File.OpenRead("Studios.stc"))
                {
		            Catalog = (List<Studio>)BF.Deserialize(file);
                }                                
            }
            catch (SerializationException)
            {
                Log.LogWarning("Incompatible versions of studio lists");
            }
            catch (FileNotFoundException)
            {
                Log.LogError("Studios file not found");
            }
            
            
            Log.LogInfo(String.Format("Loaded {0} studios", Catalog.Count));
            
            return Catalog.Count;
        }

        private void LoadToGUI(Studio studio)
        {
            namelabel.Text = studio.Name;
            addresslabel.Text = studio.Addr.ToString();
            distlabel.Text = studio.Discrict;
            metrolabel.Text = studio.Subway;
            phonetext.Text = studio.Phones;

            descripttextBox.Text = studio.Description;


            photoPanel1.Controls.Clear();
            foreach (Photo item in studio.Photos)
            {

                PictureBoxComment photoBox = new PictureBoxComment();
                photoBox.LoadPhoto(item);
                photoPanel1.Controls.Add(photoBox);
            }

            rentlistBox.Items.Clear();
            foreach (Rent item in studio.Rents)
            {
                rentlistBox.Items.Add(item.Item.Name);
            }

            roomPanel.Controls.Clear();
            foreach (Room item in studio.Rooms)
            {
                RoomView roomControl = new RoomView();
                
                roomControl.LoadRoom(item);

                roomPanel.Controls.Add(roomControl);
                roomControl.Dock = DockStyle.Fill;
            }

            priceGrid.Rows.Clear();
            foreach (PriceSchedule.Timing item in studio.Schedule.Intervals)
            {
                int id = priceGrid.Rows.Add();
                priceGrid[0, id].Value = item.ToString();
            }

            for (int colls = 0; colls < 7; colls++)
                for (int rows = 0; rows < priceGrid.Rows.Count; rows++)
                {
                    //TODO: Coloring depending on availability
                    //priceGrid[colls + 1, rows].Style.BackColor = Color.LightGreen;
                    priceGrid[colls + 1, rows].Value = studio.Schedule.Table[rows][colls];
                }

        }

        public static void BrowseURL(String url)
        {
            Browser browserForm = new Browser();
            browserForm.LoadURL(url);
            browserForm.Show();
        }
        private int LoadFilesToMerge()
        {
            string[] files = Directory.GetFiles(".", "*.std");
            
            Studio stud;

            // result - is number of successfully added files 
            int result = 0;

            for (int i = 0; i < files.Length; i++)
            {
                stud = Studio.FromFile(files[i]);
                if (stud == null) continue;

                if (stud.CheckKey())
                {
                    Studio oldOne = Catalog.Find(delegate(Studio studio) { return stud.Name == studio.Name; });
                    // Studio with Name doesnt exist
                    if (oldOne == null)
                    {
                        result++;
                        Catalog.Add(stud);

                    }
                    // Studio with such name already exeists in Catalog
                    else
                    {
                        // Checking whether loaded file contains newer version of this studio or not..
                        // If true - update, else - ignore.
                        if (oldOne.Stamp < stud.Stamp)
                        {
                            int id = Catalog.IndexOf(oldOne);
                            Catalog[id] = stud;
                        }
                    }
                    try
                    {
                        File.Move(files[i], "Store\\" + files[i]);
                    }
                    catch { }
                }
                else
                    Log.LogWarning(String.Format("Studio {0} has invalid key({1})", stud.Name, stud.Key));
            }
            return result;
        }
        

        public MainWindow()
        {      
            InitializeComponent();            

            LoadList();
            if (LoadFilesToMerge() > 0)
                SaveList();

            foreach (Studio item in Catalog)
                listStudio.Items.Add(item.Name);
            listStudio.SelectedIndex = Math.Max(LoadList() - 1, -1);
        }

        private void ShowCreateForm()
        {
            CreateWindow createForm = new CreateWindow();
            createForm.ShowDialog(this);
        }

        private void listStudio_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = listStudio.SelectedIndex;
            string name = (string)listStudio.Items[index];
                      

            foreach (Studio item in Catalog)
                if (item.Name == name)
                    LoadToGUI(item);            
        }

        
        
        private void rentlistBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rentlistBox.SelectedIndex == -1)
                return;

            Rent item = viewedStudio.Rents[rentlistBox.SelectedIndex];


            rentDescript.Text = item.Item.Description;
            rentURL.Text = item.Item.URL;

            rentPrice.Text = item.Price.ToString();
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            ServiceRef.StudioSrvClient client = new StuCat.ServiceRef.StudioSrvClient();

            Studio stdcont = new Studio();
           
            
           
            MessageBox.Show("Не реализовано....  :( ");
        }

      
        private void button1_Click(object sender, EventArgs e)
        {
            ShowCreateForm();
        }

        private void rentURL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BrowseURL(rentURL.Text);  
        }

        private void priceGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void minipanel6_Paint(object sender, PaintEventArgs e)
        {

        }

        private void minipanel3_Paint(object sender, PaintEventArgs e)
        {

        }



   
    }
}
